import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split

enc = OneHotEncoder()
df = pd.read_excel("D:\\A_TXT文件\\sheet.xlsx", sheet_name="Sheet1")
df_encoded = pd.get_dummies(df, columns=['age', 'income', 'students', 'credit'])

# 分离特征和标签，特征集为 X
X = df_encoded.drop('buy', axis=1)
y = df_encoded['buy']
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, y, test_size=0.2, random_state=666)

mnb = MultinomialNB(alpha=1.0e-10, fit_prior=True, class_prior=None)
mnb.fit(Xtrain, Ytrain)

# 创建新样本数据的数据框，并进行与训练数据相同的预处理
new_samples = pd.DataFrame([['>40', '高', '是', '优'], ['31~40', '低', '否', '中']], columns=['age', 'income', 'students', 'credit'])
new_samples_encoded = pd.get_dummies(new_samples, columns=['age', 'income', 'students', 'credit'])

# 获取训练数据的特征列名
train_feature_names = Xtrain.columns

# 确保新样本数据具有与训练数据相同的特征列
new_samples_encoded = new_samples_encoded.reindex(columns=train_feature_names, fill_value=0)

predictions = mnb.predict(new_samples_encoded)
print("新样本的预测结果：", predictions)